<template>
  <div class="">
    <ProTable
        ref="proTableRef"
        :tableSource="tableData"
        :columns="columns"
        @onload="getList"
        @add="table_add"
        :pagination="false"
        :initParam="{}"
    >
      <template #bodyCell="{record,column}">
        <template v-if="column.dataIndex === 'operation'">
          <ProButton type="link" :options="$format.btn_del($format.btn_disabled(['add','edit','delete'],record.disabled),record)" :cancel="tabke_item_cancel" :finished="(status)=>table_item_finished(status,record)"></ProButton>
        </template>
        <template v-else>
          {{ $format.str(record[column.dataIndex]) }}
        </template>
      </template>
    </ProTable>

    <pro-modal v-model="visable" title="标题" @close="modal_cancel">
      <a-row class="pl-2">
        <a-col :span="6" class="text-right pr-1">父级:</a-col>
        <a-col :span="14" class="pl-1">{{ edit_info ? $format.str(edit_info?.p_name) : '-' }}</a-col>
      </a-row>
      <ProForm ref="lgformRef" :initParam="{}" :configure="configure"  v-bind="formOptions"></ProForm>
      <template #footer>
        <ProButton type="primary" :options="['submit','close']" :cancel="modal_cancel" :finished="modal_finished"></ProButton>
      </template>
    </pro-modal>
  </div>
</template>

<script setup lang="ts">
import {getCurrentInstance, nextTick, onMounted, ref} from "vue";
import ProTable from "@/components/ProTable"
import ProForm from "@/components/ProForm"
import type {TableProps, TableInstance} from "@/components/ProTable";
import type { FormInstance, FormProps} from "@/components/ProForm";
import {buttonType} from "@/components/ProButton/interface";

// import {useI18n} from "vue-i18n";
import { get} from "lodash";
import fetchApi from "@/api/system/dept";
import fetchApiCommpn from "@/api/common"

// const { t,locale } = useI18n({inheritLocale: true,useScope: 'local'})
const { proxy }:any = getCurrentInstance();

const tableData = ref()

const columns:TableProps['columns'] = [
  {
    dataIndex:"s_key",
    title:"关键字",
    search:true,
    hidden:true
  },
  {
    dataIndex:"s_manager",
    title:"部门负责人",
    search:true,
    hidden:true
  },
  {
    dataIndex:"name",
    title:"部门"
  },
  {
    dataIndex:"code",
    title:"编码"
  },
  {
    dataIndex:"manager_name",
    title:"部门负责人"
  },
  {
    width:270,
    dataIndex:"operation",
    title:"操作"
  }
]

const proTableRef = ref<TableInstance>();
const visable = ref(false);
const lgformRef = ref<FormInstance>();


const configure = ref<FormProps['configure']>([{"type":"text","label":"名称","span":24,"prop":"name","searchInitParam":"","enum":[],
  "searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
  "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"text","label":"编码","span":24,"prop":"code","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":true,"max":100},
    "rules":[{"type":"string","required":true,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"text","label":"简称","span":24,"prop":"simple_name","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false,"max":100},
    "rules":[{"type":"string","required":false,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"textarea","label":"备注","span":24,"prop":"remark","searchInitParam":"","enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false,"max":100},
    "rules":[{"type":"string","required":false,"max":100,"min":1,"message":"请输入1-100个字符","trigger":["change","blur"]}]},
  {"type":"number","label":"排序","span":24,"prop":"sort","searchInitParam":0,"enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":true,"max":100,"min":0},
    "rules":[{"type":"number","required":true,"max":100,"min":0,"message":"请输入0-100之间数字","trigger":["change","blur"]}]},
  {"type":"select","label":"负责人","span":24,"prop":"manager","searchInitParam":'',"enum":[],
    "searchProps":{"disabled":false,"readonly":false,"required":false},"rules":[{"required":false,"trigger":["change","blur"]}]}])
const formOptions = {"showButton":false,"isvalidate":true,"layout":[6,14],"colNum":1}

const edit_info = ref<null|any>(null);
const is_add = ref(true);

onMounted(()=>{
  getConfigure()
})

const getConfigure = async ()=>{
  const res = await fetchApiCommpn.optionsUser()
  if(res.code === 200 && configure.value){
    proxy.$chain(configure.value)
    .find(['prop','manager'])
    .set('enum', res.data.map((v)=>({label:v.username,value:v.id}))).value()
  }
}

const getList = async (params:any)=>{
  const res = await fetchApi.sysDeptList(params)
  if(res.code === 200){
    tableData.value = res.data
  }
}

// 表格行按钮点击事件
const table_item_finished = async (status:buttonType,item:any)=>{
  if(['add','edit','view'].includes(status)) visable.value = true

    if(status === 'edit'){
      is_add.value = false
      await nextTick();
      await find_by_id(item)
    }

    if(status === 'add') {
      is_add.value = true
      edit_info.value = {pid:item.id,p_name:item.name}
    }

  if(status === 'delete'){
    return await table_delete(item)
  }
  return Promise.resolve()
}

// 根据id查询详情信息
const find_by_id = async (item:APISYSTEMDEPT.SysDeptList)=>{
  const res = await fetchApi.sysFindDept(item.id)
  if(res.code === 200){
    edit_info.value = {id:item.id,pid:res.data.pid,p_name:item.p_name}
    lgformRef.value?.updateFormByKey('code',get(res.data,'code'))
    lgformRef.value?.updateFormByKey('name',get(res.data,'name'))
    lgformRef.value?.updateFormByKey('simple_name',get(res.data,'simple_name'))
    lgformRef.value?.updateFormByKey('remark',get(res.data,'remark'))
    lgformRef.value?.updateFormByKey('sort',get(res.data,'sort'))
    lgformRef.value?.updateFormByKey('manager',get(res.data,'manager'))
  }
}

// 删除
const table_delete = async (item:APISYSTEMDEPT.SysDeptList)=>{
  const res = await fetchApi.sysDelDept(item.id)
  proxy.$format.response(res)
  proTableRef.value?.refresh()
}

const table_add = ()=>{
  visable.value = true
}

const tabke_item_cancel = ()=>{
  alert("取消")
}

const modal_cancel = ()=>{
  console.log("点击取消")
  visable.value = false
  lgformRef.value?.resetForm()
  edit_info.value = null
  is_add.value = true
}
const modal_finished = async (status:buttonType)=> {
  switch (status){
    case "submit":
      return await modal_submit();
  }
}

// 提交
const modal_submit = async ()=>{
  try {
    const data = await lgformRef.value?.validate()
    if(!data) return false
    let res;
    if(is_add.value) res = await fetchApi.sysAddDept({...data,pid:get(edit_info.value,'pid',0)});
    if(!is_add.value) res = await fetchApi.sysUpdateDept({...data,id:edit_info.value.id,pid:edit_info.value.pid});

    proxy.$format.response(res)
    proTableRef.value?.refresh();
    await modal_cancel()

  }catch (e) {
    console.log("提交",e)
  }
}


</script>

<style scoped lang="less">

</style>

